package com.example.netty.bio;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @author created by wangyang
 * email:techyang.wangy@ymm56.com
 * company: yunmanman
 * @date 2018/12/13 4:28 PM
 */
public class PlainBIOServer {

    @SuppressWarnings("unchecked")
    public void server(int port) throws IOException {
        final ServerSocket ss = new ServerSocket(port);

        try{
            while (true) {
                final Socket s = ss.accept();
                System.out.println("Accept Connection from " + s);

                new Thread(() -> {
                    OutputStream out;
                    try{
                        out = s.getOutputStream();
                        //write message to connected client
                        out.write("Hi!\r\n".getBytes(Charset.forName("UTF-8")));
                        out.flush();
                        //close connection once message written and flushed
                        s.close();
                    }catch(IOException e){
                        try {
                            s.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }).start();//start thread to begin handling


            }
        }catch (Exception e) {
            System.err.println(e);
            ss.close();
        }
    }
}
